package web;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.ModifySales;
import model.UploadFileClass;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadFile
 */
public class UploadFile extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UploadFile() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher view = request.getRequestDispatcher("uploadsalesfile.jsp");
		view.forward(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uploadResult = "";
		String parseResult = "";
		UploadFileClass up = new UploadFileClass();
		up.init(getServletContext().getInitParameter("fileuploadpath"));

		// Parse the request to get file items.
		if (up.Upload(request)) {
			uploadResult = "Uploadarea realizata cu succes";
			ModifySales ms = new ModifySales();
			ms.setFile(up.getFile());
			if(ms.ReadFile())
				parseResult = "Parsarea datelor completata cu succes!";
			else
				parseResult = "Parsarea datelor a intampinat o problema! Starea datelor initiala nu a fost alterata";
		} else
			uploadResult = "Uploadarea a intampinat o problema.";
		// we erase the file from the server
		if(up.getFile().delete()){
			System.out.println("sa sters");
		}
		else System.out.println("nu sa sters");
		request.setAttribute("uploadResult", uploadResult);
		request.setAttribute("parseResult", parseResult);
		// RequestDispatcher view = request.getRequestDispatcher("sales.do");
		// view.forward(request, response);
		
		response.sendRedirect(response.encodeRedirectURL("sales.do"));

	}

}
